<?php

declare(strict_types=1);

namespace app\api\controller\Order;

use app\BaseController;
use app\common\model\Product\Cart as CartModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Address as AddressModel;
use app\common\model\Order\Order as OrderModel;
use app\common\model\Order\Product as OrderProModel;
use app\common\model\Product\Product as ProductModel;
use app\common\model\User\Record as RecordModel;
use app\common\validate\Order\Order as OrderValiDate;
use app\common\validate\Order\Product as OrderProValiDate;
use app\common\validate\User\Record as RecordValiDate;
use think\exception\ValidateException;

class Order extends BaseController
{
    public function index()
    {
        $userid = $this->request->param('userid');
        $status = $this->request->param('status');

        $where = [];

        if ($userid) {
            $where['userid'] = $userid;
        }

        if ($status) {
            $where['status'] = $status;
        }
        $OrderList = OrderModel::where($where)->select();

        foreach ($OrderList as &$item) {
            $OrderProduct = OrderProModel::withJoin(['products'])->where(['orderid' => $item['id']])->select();

            $item['OrderProduct'] = $OrderProduct;
        }

        $this->success('查询成功', null, $OrderList);
    }
    // 新增订单
    public function add()
    {
        /* 
            order => 新增一个订单 （创建model,validate）
            order_product => 新增一个订单商品记录 （创建model,validate）
            product => 库存减去下单库存 (更新数据的操作)
            user => 扣除下单的积分 (更新数据的操作)
            user_record => 新增购物记录 (新增数据的操作)
            cart => 下单成功后购物车的里相关数据删除 (删除数据的操作)
        */
        try {
            // 用户id
            $userid = $this->request->param('userid');
            // 购物车id
            $CartIds = $this->request->param('cartid');
            // 用户收货地址id
            $addrid = $this->request->param('addrid');
            // 订单备注
            $content = $this->request->param('content');
            // 查询用户是否存在
            $User = UserModel::find($userid);
            if (!$User) {
                throw new \Exception('用户不存在');
            }
            // 查询用户收货地址是否存在
            $address = AddressModel::where(['userid' => $userid, 'id' => $addrid])->find();
            if (!$address) {
                throw new \Exception('收货地址不存在');
            }
            // 查询购物车数据
            $CartList = CartModel::withJoin(['product'])->whereIn('cart.id', $CartIds)->select();
            // 订单总价变量
            $total = 0;
            // 购物车id转为数组
            $CartIdArr = !empty($CartIds) ? explode(',', $CartIds) : [];
            // 判断购物车id是否存在
            foreach ($CartList as $key => $item) {
                if (!in_array($item['id'], $CartIdArr)) {
                    throw new \Exception('购物车商品数据不存在');
                }
                // 库存判断
                if ($item['nums'] > $item['product']['stock']) {
                    throw new \Exception("{$item['product']['name']}库存不足",);
                }
                // 积分判断
                $point = bcsub((string)$User['point'], (string)$item['total']);
                if ($point < 0) {
                    throw new \Exception('积分不足，请及时充值');
                }
                // 计算总价
                $total += $item['total'];
            }
            // 开启事务
            OrderModel::startTrans();
            OrderProModel::startTrans();
            UserModel::startTrans();
            RecordModel::startTrans();
            ProductModel::startTrans();
            CartModel::startTrans();
            // 封装订单数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code('ASK'),
                'total' => $total,
                'content' => $content,
                'status' => 1
            ];
            // 验证订单数组
            validate(OrderValiDate::class)->check($OrderData);
            // 新增订单
            $OrderStatus = OrderModel::create($OrderData);
            // 判断是否新增成功
            if ($OrderStatus === FALSE) {
                throw new \Exception('新增订单失败');
            }

            // 订单商品
            $OrderProData = [];

            foreach ($CartList as $key => $item) {
                $OrderProData[] = [
                    'orderid' => $OrderStatus->id,
                    'proid' => $item['product']['id'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                    'userid' => $userid
                ];
            }
            // 验证数据
            foreach ($OrderProData as $key => $value) {
                validate(OrderProValiDate::class)->check($value);
            }

            // 实例化模型
            $OrderProModel = new OrderProModel();
            // 批量新增
            $OrderProStatus = $OrderProModel->saveAll($OrderProData);
            // 判断新增是否成功
            if ($OrderProStatus === FALSE) {
                throw new \Exception('新增订单商品失败');
            }
            // 更新商品库存
            $ProductData = [];

            foreach ($CartList as $key => $item) {
                $ProductData[] = [
                    'id' => $item['product']['id'],
                    'stock' => bcsub((string)($item['product']['stock']), (string)$item['nums']),
                ];
            }


            $ProductModel = new ProductModel();

            $ProductStatus = $ProductModel->saveAll($ProductData);

            if ($ProductStatus === FALSE) {
                throw new \Exception('更新商品库存失败');
            }

            // 更新用户积分
            $User->point = bcsub((string)($User['point']), (string)$total);
            // 保存
            $UserStatus = $User->save();
            // 判断是否成功
            if ($UserStatus === FALSE) {
                throw new \Exception('更新用户积分失败');
            }

            // 新增消费记录
            $RecordData = [
                'point' => $total,
                'content' => "您的订单{$OrderData['code']}消费了{$total}积分",
                'state' => 5,
                'userid' => $userid
            ];
            // 验证数据
            validate(RecordValiDate::class)->check($RecordData);
            // 新增
            $RecordStatus = RecordModel::create($RecordData);
            // 判断是否成功
            if ($RecordStatus === FALSE) {
                throw new \Exception('新增消费记录失败');
            }
            // 购物车执行删除
            $CartStatus = CartModel::destroy($CartIdArr);

            if ($CartStatus === FALSE) {
                throw new \Exception('删除购物车的数据失败');
            }
        } catch (ValidateException $e) {
            OrderModel::rollback();
            CartModel::rollback();
            OrderProModel::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            ProductModel::rollback();
            $this->error($e->getError());
        } catch (\Exception $error) {
            OrderModel::rollback();
            CartModel::rollback();
            OrderProModel::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            ProductModel::rollback();
            $this->error($error->getMessage());
        }
        OrderModel::commit();
        OrderProModel::commit();
        UserModel::commit();
        RecordModel::commit();
        ProductModel::commit();
        CartModel::commit();

        $this->success('订单支付成功', null, ['orderid' => $OrderStatus->id]);
    }
    // 新增订单（立即购买）
    public function gain()
    {
        // order => 新增一个订单 （创建model,validate）
        // order_product => 新增一个订单商品记录 （创建model,validate）
        // product => 库存减去下单库存 (更新数据的操作)
        // user => 扣除下单的积分 (更新数据的操作)
        // user_record => 新增购物记录 (新增数据的操作)
        try {
            // 用户id
            $userid = $this->request->param('userid');
            // 购物车id
            $proid = $this->request->param('proid');
            // 用户收货地址id
            $addrid = $this->request->param('addrid');
            // 订单备注
            $content = $this->request->param('content');
            // 查询用户是否存在
            $User = UserModel::find($userid);
            if (!$User) {
                throw new \Exception('用户不存在');
            }
            // 查询用户收货地址是否存在
            $address = AddressModel::where(['userid' => $userid, 'id' => $addrid])->find();
            if (!$address) {
                throw new \Exception('收货地址不存在');
            }
            // 查询商品数据
            $Product = ProductModel::find($proid);
            // 库存判断
            if ($Product['stock'] == 0) {
                throw new \Exception("商品库存不足");
            }
            // 积分判断
            $point = bcsub((string)$User['point'], (string)$Product['price']);
            if ($point < 0) {
                throw new \Exception('积分不足，请先充值');
            }
            // 开启事务
            OrderModel::startTrans();
            OrderProModel::startTrans();
            UserModel::startTrans();
            RecordModel::startTrans();
            ProductModel::startTrans();
            // 封装订单数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code('ASK'),
                'total' => $Product['price'],
                'content' => $content,
                'status' => 1
            ];
            // 验证订单数组
            validate(OrderValiDate::class)->check($OrderData);
            // 新增订单
            $OrderStatus = OrderModel::create($OrderData);
            // 判断是否新增成功
            if ($OrderStatus === FALSE) {
                throw new \Exception('新增订单失败');
            }

            // 订单商品
            $OrderProData = [
                'orderid' => $OrderStatus->id,
                'proid' => $Product['id'],
                'nums' => 1,
                'price' => $Product['price'],
                'total' => $Product['price'],
                'userid' => $userid
            ];

            // 验证数据
            validate(OrderProValiDate::class)->check($OrderProData);
            // 新增
            $OrderProStatus = OrderProModel::create($OrderProData);
            // 判断新增是否成功
            if ($OrderProStatus === FALSE) {
                throw new \Exception('新增订单商品失败');
            }

            // 更新商品库存
            $Product->stock = $Product['stock'] - 1;
            $ProductStatus = $Product->save();

            if ($ProductStatus === FALSE) {
                throw new \Exception('更新商品库存失败');
            }
            // 更新用户积分
            $User->point = bcsub((string)($User['point']), (string)$Product['price']);
            // 保存
            $UserStatus = $User->save();
            // 判断是否成功
            if ($UserStatus === FALSE) {
                throw new \Exception('更新用户积分失败');
            }

            // 新增消费记录
            $RecordData = [
                'point' => $Product['price'],
                'content' => "您的订单{$OrderData['code']}消费了{$Product['price']}积分",
                'state' => 5,
                'userid' => $userid
            ];
            // 验证数据
            validate(RecordValiDate::class)->check($RecordData);
            // 新增
            $RecordStatus = RecordModel::create($RecordData);
            // 判断是否成功
            if ($RecordStatus === FALSE) {
                throw new \Exception('新增消费记录失败');
            }
        } catch (ValidateException $e) {
            OrderModel::rollback();
            OrderProModel::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            ProductModel::rollback();
            $this->error($e->getError());
        } catch (\Exception $error) {
            OrderModel::rollback();
            OrderProModel::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            ProductModel::rollback();
            $this->error($error->getMessage());
        }
        OrderModel::commit();
        OrderProModel::commit();
        UserModel::commit();
        RecordModel::commit();
        ProductModel::commit();
        $this->success('订单支付成功', null, ['orderid' => $OrderStatus->id]);
    }
    // 订单详情
    public function info()
    {
        $orderid = $this->request->param('orderid');

        $Order = OrderModel::withJoin('address')->find($orderid);

        if (!$Order) {
            $this->error('订单不存在，请重新选择');
        }

        $OrderProduct = OrderProModel::withJoin('products')->where(['orderid' => $orderid])->select();

        if (!$OrderProduct) {
            $this->error('订单不存在，请重新选择');
        }
        $data = [
            'Order' => $Order,
            'OrderProduct' => $OrderProduct
        ];
        $this->success('查询成功', null, $data);


        /* 
            用户收货地址
            订单数据
            订单商品 => product
        */
    }
    // 退货
    public function after()
    {
        $orderid = $this->request->param('orderid');
        // 查询订单是否存在
        $Order = OrderModel::where(['id' => $orderid])->find();
        if (!$Order) {
            $this->error('订单不存在');
        }
        // 查询用户是否存在
        $User = UserModel::find($Order['userid']);
        if (!$User) {
            $this->error('用户不存在');
        }
        $Order->status = -2;
        $OrderStatus = $Order->save();
        if ($OrderStatus === FALSE) {
            $this->error('申请退货失败');
        } else {
            $this->success('申请退货成功，请等待审核');
        }
    }
    // 确认收货
    public function receipt(){
        $orderid = $this->request->param('orderid');
        // 查询订单是否存在
        $Order = OrderModel::where(['id' => $orderid])->find();
        if (!$Order) {
            $this->error('订单不存在');
        }
        // 查询用户是否存在
        $User = UserModel::find($Order['userid']);
        if (!$User) {
            $this->error('用户不存在');
        }
        $Order->status = 3;
        $OrderStatus = $Order->save();
        if ($OrderStatus === FALSE) {
            $this->error('确认收货失败！');
        } else {
            $this->success('确认收货成功！');
        }
    }
    // 评分
    public function rate(){
        $orderid = $this->request->param('orderid');
        $rate = $this->request->param('rate');
        // 查询订单是否存在
        $Order = OrderModel::where(['id' => $orderid])->find();
        if (!$Order) {
            $this->error('订单不存在');
        }
        // 查询用户是否存在
        $User = UserModel::find($Order['userid']);
        if (!$User) {
            $this->error('用户不存在');
        }
        $data=[
            'rate'=>$rate,
            'status'=>4
        ];
        $result=OrderModel::update($data,['id'=>$Order['id']]);
        if ($result === FALSE) {
            $this->error('评价失败！');
        } 
        if ($rate>=3) {
            $this->success('您的满意，就是我们最大的动力');
        }else{
            $this->success('非常抱歉没有给您带来愉快的购物体验');
        }
    }
    // 删除订单
    public function del(){
        $orderid = $this->request->param('orderid');
        // 查询订单是否存在
        $Order = OrderModel::where(['id' => $orderid])->find();
        if (!$Order) {
            $this->error('订单不存在');
        }
        // 查询用户是否存在
        $User = UserModel::find($Order['userid']);
        if (!$User) {
            $this->error('用户不存在');
        }
        $result=OrderModel::destroy($orderid);
        if ($result === FALSE) {
            $this->error('删除失败！');
        } 
        $this->success('删除成功！');
    }
}
